import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';
import 'package:sqflite_common_ffi_web/sqflite_ffi_web.dart';
import 'package:sqflite/sqflite.dart';
import 'providers/transaction_provider.dart';
import 'screens/home_screen.dart';
import 'utils/theme_util.dart';
import 'services/notification_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 全局导航键
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// ThemeProvider 用于管理应用的主题状态
class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.system;

  ThemeMode get themeMode => _themeMode;

  void setThemeMode(ThemeMode mode) {
    _themeMode = mode;
    notifyListeners();
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 为Web平台初始化sqflite
  if (kIsWeb) {
    databaseFactory = databaseFactoryFfiWeb;
  }

  // 初始化通知服务
  try {
    await NotificationManager().initialize();
    if (kDebugMode) {
      debugPrint('NotificationManager initialized successfully');
    }
  } catch (e) {
    if (kDebugMode) {
      debugPrint('Failed to initialize NotificationManager: $e');
    }
  }

  // 初始化数据同步服务
  final transactionProvider = TransactionProvider();
  await transactionProvider.initializeDataSync();

  // 获取 SharedPreferences 实例
  final prefs = await SharedPreferences.getInstance();

  // 设置 GitHub Token
  const githubToken =
      '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'; // 请替换为你的 GitHub Token
  await prefs.setString('github_token', githubToken);

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => transactionProvider),
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeProvider>(
      // 使用 Consumer 来监听 ThemeProvider 的变化
      builder: (context, themeProvider, child) {
        return MaterialApp(
          navigatorKey: navigatorKey,
          title: 'FinTrack',
          theme: ThemeUtil.getLightTheme(),
          darkTheme: ThemeUtil.getDarkTheme(),
          themeMode: themeProvider.themeMode, // 从 ThemeProvider 获取 themeMode
          home: const HomeScreen(),
          debugShowCheckedModeBanner: false,
        );
      },
    );
  }
}
